package cn.dapeng.rpc.common.handler;

import cn.dapeng.rpc.common.PkmRequestMessage;
import cn.dapeng.rpc.common.RequestTypeEnum;
import cn.dapeng.rpc.common.RpcResponse;
import cn.dapeng.rpc.common.serial.SerializeFactory;
import cn.dapeng.rpc.common.util.MagicNumberUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerRequestHandlerV2 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " closed ...... ");
        super.channelInactive(ctx);
        ctx.channel().close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        PkmRequestMessage request = (PkmRequestMessage) msg;

        int serialType = MagicNumberUtil.getSerialVersion(request.getMagic());

        int version = MagicNumberUtil.getVersion(request.getMagic());

        // 把消息传给客户端
        String ioThreadName = Thread.currentThread().getName();

        // 注意下面这两行，一个是在本线程执行，一个是在其他线程中执行
        ctx.executor().execute(() -> {
            //ctx.executor().parent().execute(() -> {

            try {
                String executeThreadName = Thread.currentThread().getName();

                RpcResponse response = new RpcResponse();
                response.setRequestId(request.getRequest().getRequestId());
                response.setResult("ioThread:" + ioThreadName + " execThread:" + executeThreadName + " args:" + request.getRequest().getParameters()[0]);

                byte[] contentBody = SerializeFactory.serial(response, serialType);

                int magic = MagicNumberUtil.getMagic(version, 0, contentBody.length, serialType, RequestTypeEnum.RESPONSE.ordinal());

                ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(Integer.BYTES + contentBody.length);
                byteBuf.writeInt(magic);
                byteBuf.writeBytes(contentBody);
                ctx.writeAndFlush(byteBuf);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

    }
}
